package com.xzs.kit.db.listener;

import com.xzs.kit.db.annotaion.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;


import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author : Victor.Xiao
 * @date : 2017/12/02 17:17
 * @description : 初始化service的dao
 */
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextListener.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
//        if(null == contextRefreshedEvent.getApplicationContext().getParent()) {
            LOGGER.info(">>>>>>>>>>>>>>>>>>  spring初始化完毕 <<<<<");
            // spring初始化完毕后，通过反射调用所有使用BaseService注解的initDao方法
            Map<String, Object> baseServices = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(BaseService.class);
            for(Object service : baseServices.values()) {
                LOGGER.info(">>>>>>>>>>>>>>>>>> {}.initDao()", service.getClass().getName());
                try {
                    Method initMapper = service.getClass().getMethod("initDao");
                    initMapper.invoke(service);
                } catch (Exception e) {
                    LOGGER.error("初始化BaseService的initDao方法异常", e);
                    e.printStackTrace();
                }
            }

//        }
    }

}
